/*
 * 活动管理
 * @date 2016/5/5
 */

//列表每页显示条数
var perPage = 15;

//是否请求完成标识
var loadBool = true;

// 优惠券id变量参数
var couponNum = 0;

// 页面初始化
$(function () {
    list();
});

// 清空查询条件
$(document).delegate("#empty", "click", function () {
    $("#state").val("-1");
    $("#namepattern").val("");
    $("#starttimeAfter").val("");
    $("#endtimeBefore").val("");
    $("#user").val("-1");
    $("#cppattern").val('');
    $("#activityList").empty();
    list();
});

// 查询活动列表
$(document).delegate("#query", "click", function () {
    list();
});

function list() {
    $("#curPage").text(0);
    $("#pages").text(0);
    getActivityList(1);
}

//下一页
$(document).delegate("#nextPage", "click", function () {
    var curPage = Number($("#curPage").text());
    var pages = Number($("#pages").text());
    if (curPage == pages) {
        return;
    }
    getActivityList(curPage + 1);
});

//上一页
$(document).delegate("#lastPage", "click", function () {
    var curPage = Number($("#curPage").text());
    if (curPage <= 1) {
        return;
    }
    getActivityList(curPage - 1);
});

// 返回上一页
function back(elem) {
    elem.on('click', "#back", function () {
        is_incity = -1;
        layer.closeAll();
    });
}

// 标记业务分类
function bussinessMark(elem) {
    elem.on('click', "input[type='checkbox']", function () {
        var bussiness = '';
        if (elem.find("#city").prop("checked")) {
            if (elem.find("#busAll").prop("checked") || elem.find("#citypin").prop("checked") || elem.find("#citybao").prop("checked") || elem.find("#package").prop("checked")) {
                is_incity = -1;//城际和市内
            } else {
                is_incity = 1;//市内
                bussiness = '市内';
            }
        } else {
            is_incity = 0;//城际
            bussiness = '城际';
        }
        if (is_incity != -1) {
            elem.find('.route-part-control .line-model').each(function () {
                var start = $(this).find('input:first-child').val();
                if (start.indexOf(bussiness) == -1) {
                    $(this).find('input:first-child').val('');
                    $(this).find('input:nth-child(2)').val('');
                }
            });
        }
    });
}

//// 根据活动开始时间过滤可选择的优惠券
//function filtCoupon(elem, data) {
//    var newData = [];
//    var startTime = elem.find('#starttime').val();
//    if (!startTime) {
//        return data;
//    }
//    var startTimestamp = new Date(startTime.replace(/-/g, '/')).getTime();
//    for (var i = 0; i < data.length; i++) {
//        if (Number(data[i].target) != -1) {
//            if (Number(data[i].target) <= startTimestamp) {
//                continue;
//            }
//        }
//        newData.push(data[i]);
//    }
//    return newData;
//}

//生成活动数据
function generateActivityData(data) {
    var lines = [], bussiness = '', user = '', rewards = [], timeNode = '', channel = '', totalcount = '', countperuser = '', state = '';
    var lineType = '全部';//路线类型，0：全部，1：全部城际，2：全部市内
    var busi = Number(data.targetbusiness); //业务
    if (busi == -1) {
        bussiness = "全部";
    } else {
        var busiArray = new Array(0, 0, 0, 0);
        for (var i = 3; i >= 0; i--) {
            var j = parseInt(busi / (Math.pow(2, i)));
            if (j > 0) {
                busiArray[i] = 1;
            }
            busi %= (Math.pow(2, i));
            if (busi == 0) {
                break;
            }
        }
        bussiness += busiArray[0] ? "城际拼车;" : '';
        bussiness += busiArray[1] ? "城际包车;" : '';
        bussiness += busiArray[2] ? "小件快递;" : '';
        bussiness += busiArray[3] ? "市内打车;" : '';
        if (busiArray[3]) {
            if (!busiArray[0] && !busiArray[1] && !busiArray[2]) {
                lineType = '全部市内';
            }
        } else {
            lineType = '全部城际';
        }
    }
    if (data.targetline) {
        for (var i = 0; i < data.targetline.length; i++) { //路线
            if (data.targetline[i] == "*") {
                lines = lineType;
                break;
            }
            lines += data.targetline[i].line_name + ';';
        }
    }

    switch (data.targetuser) {//对象
        case "-1":
            user = "全部";
            break;
        case "0":
            user = "老用户";
            break;
        case "1":
            user = "新用户";
            break;
    }
    if (data.rewards) {//奖励
        for (var i = 0; i < data.rewards.length; i++) {
            rewards += "<p>" + data.rewards[i].friendlyid + '-' + data.rewards[i].name + '*' + data.rewards[i].cnt + "</p>";
        }
    } else {
        rewards = '';
    }
    switch (data.timenode) {//节点
        case "0":
            timeNode = "任何时刻";
            break;
        case "1":
            timeNode = "登录";
            break;
        case "2":
            timeNode = "下单成功";
            break;
        case "3":
            timeNode = "订单完成";
            break;
        case "4":
            timeNode = "线上支付成功";
            break;
    }
    channel = data.channel ? data.channel.name : '全部渠道';//渠道
    totalcount = data.totalcount > -1 ? data.totalcount : '不限制';//总份数
    countperuser = data.countperuser > -1 ? data.countperuser : '不限制';//单人最多可得份数
    var opt = '';//操作
    switch (data.state) {//状态
        case -1:
            state = "全部";
            break;
        case 0:
            state = "进行中";
            if (data.totalcount > -1) {//进行中   停用，追加，统计
                opt = "<a class='modify invalid' href='javascript:void(0);'>修改</a><a class='use' state='2' href='javascript:void(0);'>停用</a><a class='tacked' href='javascript:void(0);'>追加</a>";
            } else {
                opt = "<a class='modify invalid' href='javascript:void(0);'>修改</a><a class='use' state='2' href='javascript:void(0);'>停用</a><a class='tacked invalid' href='javascript:void(0);'>追加</a>";
            }
            break;
        case 1:
            state = "未开始";
            if (data.totalcount > -1) {//未开始   修改，停用，追加，统计
                opt = "<a class='modify' href='javascript:void(0);'>修改</a><a class='use' state='2' href='javascript:void(0);'>停用</a><a class='tacked' href='javascript:void(0);'>追加</a>";
            } else {
                opt = "<a class='modify' href='javascript:void(0);'>修改</a><a class='use' state='2' href='javascript:void(0);'>停用</a><a class='tacked invalid' href='javascript:void(0);'>追加</a>";
            }
            break;
        case 2:
            state = "未启用";
            if (data.totalcount > -1) {//未启用  修改，启用，追加，统计
                opt = "<a class='modify' href='javascript:void(0);'>修改</a><a class='use' state='1' href='javascript:void(0);'>启用</a><a class='tacked' href='javascript:void(0);'>追加</a>";
            } else {
                opt = "<a class='modify' href='javascript:void(0);'>修改</a><a class='use' state='1' href='javascript:void(0);'>启用</a><a class='tacked invalid' href='javascript:void(0);'>追加</a>";
            }
            break;
        case 3:
            state = "已停用";//已停用  统计
            opt = "<a class='modify invalid' href='javascript:void(0);'>修改</a><a class='use invalid' state='2' href='javascript:void(0);'>停用</a><a class='tacked invalid' href='javascript:void(0);'>追加</a>";
            break;
        case 4:
            state = "已结束";//已结束  统计
            opt = "<a class='modify invalid' href='javascript:void(0);'>修改</a><a class='use invalid' state='2' href='javascript:void(0);'>停用</a><a class='tacked invalid' href='javascript:void(0);'>追加</a>";
            break;
    }

    var act = {
        id: data.id,
        name: data.name,
        starttime: data.starttime,
        endtime: data.endtime,
        user: user,
        rewards: rewards,
        timenode: timeNode,
        channel: channel,
        line: lines,
        bussiness: bussiness,
        totalcount: totalcount,
        countperuser: countperuser,
        tag: data.tag,
        state: state,
        opt: opt
    };
    return act;
}

/*
 * 获取活动列表
 * @date 2016/5/5
 */
function getActivityList(curPage) {
    if (!loadBool) {
        return;
    }
    loadBool = false;
    $("#activityList").empty();
    //loading层
    var layerIndex = layer.load(2, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });

    var index = curPage - 1;
    var params = JSON.stringify({
        "state": Number($("#state option:selected").val()),
        "namepattern": $("#namepattern").val(),
        "user": Number($("#user option:selected").val()),
        "starttime_after": $("#starttimeAfter").val(),
        "endtime_before": $("#endtimeBefore").val(),
        "cppattern": $("#cppattern").val(),
        'pos': index * perPage,
        'limit': perPage
    });
    $.ajax({
        type: "POST",
        url: "/activitymanager/gactlist",
//        timeout: 5000,
        contentType: "application/json",
        dataType: "json",
        data: params,
        success: function (data) {
            layer.close(layerIndex);
            if (data.status == 0) {
                $("#pages").text(Math.ceil(data.count / perPage));
                if (data.data.length > 0) {
                    $("#curPage").text(index + 1);
                    for (var i = 0; i < data.data.length; i++) {
                        var act = generateActivityData(data.data[i]);
                        var row = "<tr line='" + act.line + "' targetbusiness='" + act.bussiness + "'>" +
                                "<td id=" + "'" + act.id + "'" + " style='display:none'></td>" +
                                "<td>" + act.name + "</td>" +
                                "<td>" + act.starttime + '~' + act.endtime + "</td>" +
                                "<td>" + act.user + "</td>" +
                                "<td>" + act.rewards + "</td>";
                        if (data.data[i].timenode == "1") { //登陆
                            row += "<td>" + act.timenode + "</td>";
                        } else {
                            row += "<td class='order-node'>" + act.timenode + "</td>";
                        }
                        row += "<td>" + act.channel + "</td>" +
                                "<td>" + act.totalcount + "</td>" +
                                "<td>" + act.countperuser + "</td>" +
                                "<td>" + act.tag + "</td>" +
                                "<td>" + act.state + "</td>" +
                                "<td>" + act.opt + "</td>" +
                                "</tr>";
                        $("#activityList").append(row);
                    }
                }
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
            loadBool = true;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.close(layerIndex);
            console.log(XMLHttpRequest);
            console.log(textStatus);
            console.log(errorThrown);
            bbx_alert_error('出错啦~');
            loadBool = true;
        }
    });
}

window.onload = function () {
    // 点击查看节点信息
    $('.table').delegate('td.order-node', 'click', function () {
        var lines = $(this).parent('tr').attr('line');
        var businiss = $(this).parent('tr').attr('targetbusiness');
        var nodeContent = ''
                + '<div class="inner-box">'
                + '<dl class="order-node-item">'
                + '<dt>订单类型:</dt>'
                + '<dd>'
                + businiss
                + '</dd>'
                + '</dl>'
                + '<dl class="order-node-item">'
                + '<dt>路&emsp;&emsp;线:</dt>'
                + '<dd>'
                + lines
                + '</dd>'
                + '</dl>'
                + '</div>';
        layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['432px', 'auto'], //宽高
            closeBtn: 0, //不显示关闭按钮
            shadeClose: true, //开启遮罩关闭
            content: nodeContent,
            success: function (layero, index) {
                // initAddPanel(layero, index);
            }
        });
    });

    // 点击追加优惠券份数
    $('.table').delegate('.tacked', 'click', function () {
        if ($(this).hasClass("invalid")) {
            return;
        }
        var sortcontent = ''
                + '<div class="inner-box">'
                + '<div class="form-group">'
                + '追加优惠券份数:'
                + '<input class="form-control" id="additionalInpput" style="width:149px;" type="text" onkeyup="digit(this,7)" oninput="digit(this,7)">'
                + '</div>'
                + '<div class="bot-button">'
                + '<input class="btn btn-lg-blue" id="submit"  type="button" value="确定">'
                + '&emsp;'
                + '<input id="cancel" class="btn btn-lg-blue" id="cancel" type="button" value="取消">'
                + '</div>'
                + '</div>';
        var id = $(this).parents('tr').find('td').eq(0).attr('id');
        layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['auto', 'auto'], //宽高
            content: sortcontent,
            success: function (layero, index) {
                additionalNumber(layero, index, id);
            }
        });
    });

    // 点击停用按钮
    $('.table').delegate('.use', 'click', function () {
        if ($(this).hasClass("invalid")) {
            return;
        }
        var id = $(this).parents('tr').find('td').eq(0).attr('id');
        var state = Number($(this).attr('state'));
        var tips = "";
        if (state == 1) {
            tips = "确定启用此活动吗？";
        } else if (state == 2) {
            tips = "确认停用？停用后不可再次启用";
        }
        layer.confirm(tips, {
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            setState(id, state);
            list();
            layer.close(index);
        });

        function setState(id, state) {
            var param = JSON.stringify({"id": id, "state": state});
            $.ajax({
                type: "POST",
                url: "/Activitymanager/sstate",
                contentType: "application/json",
                dataType: "json",
                data: param,
                success: function (data) {
                    if (data.status == 0) {

                    } else if (data.status == -501) {//session过期
                        window.location.href = '/timeout/index';
                    } else {
                        bbx_alert_error(data.message);
                    }
                },
                error: function () {
                    bbx_alert_error('出错啦~');
                }
            });
        }
    });

    //点击修改活动按钮
    $('.table').delegate('.modify', 'click', function () {
        if ($(this).hasClass("invalid")) {
            return;
        }
        var id = $(this).parents('tr').find('td').eq(0).attr('id');
        var index = layer.open({
            type: 2,
            title: false,
            closeBtn: 0, //不显示关闭按钮
            maxmin: false,
            content: '/activitymodify/amodify',
            success: function (layero, index) {
                initModifyCoupon(layero, id);
            }
        });
        layer.full(index);
    });

    /*
     * 点击添加活动按钮
     * @date 2016/5/7
     */
    $('.search-inline').delegate('#add', 'click', function () {
        var index = layer.open({
            type: 2,
            title: false,
            closeBtn: 0, //不显示关闭按钮
            maxmin: false,
            content: '/activityadd/aadd',
            success: function (layero, index) {
                initAddPanel(layero, index);
            }
        });
        layer.full(index);
    });
};

// 追加优惠券份数
function additionalNumber(layero, index, id) {
    layero.find('#submit').click(function () {
        if (layero.find('#additionalInpput').val() == "") {
            bbx_alert_error("输入份数为空!添加失败");
            layer.close(index);
            return;
        }
        var cnt = Number(layero.find('#additionalInpput').val());
        var param = JSON.stringify({"id": id, "count": cnt});
        $.ajax({
            type: "POST",
            url: "/Activitymanager/append",
            contentType: "application/json",
            dataType: "json",
            data: param,
            success: function (data) {
                if (data.status == 0) {
                    layer.msg('添加成功！', {icon: 1, time: 1000}, function () {
                        list();
                        layer.close(index);
                    });
                } else if (data.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(data.message);
                }
            },
            error: function () {
                bbx_alert_error('出错啦~');
            }
        });
    });
    layero.find("#cancel").on("click", function () {
        layer.close(index);
    });
}

// 增加优惠券
function addCouponModel(elem) {
    // 优惠券选择点击增加
    elem.on('click', '.coupon-list-model .coupon-model:last-child .coupon-buttons .increase', function () {
        _addCouponModel($(this), elem, true);
    });
    // 优惠券选择点击减
    elem.on('click', '.coupon-buttons .decrease', function () {
        _addCouponModel($(this), elem, false);
    });
}


function _addCouponModel(self, elem, isIncrease, setValue, setCnt) {
    var cnt = setCnt ? setCnt : '';
    var content = ''
            + '<div class="coupon-model">'
            + '<div class="form-group">'
            + '<input class="form-control auto-complete"  id="couponSelect' + couponNum + '" type="text"><input class="form-control form-sm-input" type="text" placeholder="填写数量" value="' + cnt + '" onkeyup="digit(this,2)" oninput="digit(this,2)">'
            + '<div class="coupon-buttons">'
            + '<button class="decrease"><i class="iconfont">&#xe60a;</i></button>'
            + '<button class="increase"><i class="iconfont">&#xe607;</i></button>'
            + '</div>'
            + '</div>'
            + '</div>';

    if (isIncrease) { //增加
        elem.find('.coupon-list-model').append(content);
        self.hide().siblings('.decrease').show();
        if (setValue) {
            getCoupon(setValue, elem.find('#couponSelect' + couponNum));
        }
        couponNum++;
    } else {//减少
        if (!self.siblings('.increase').is(':hidden')) {
            self.closest('.coupon-model').prev('.coupon-model').find('.increase').show();
        }
        self.closest('.coupon-model').remove();

        if (elem.find('.coupon-model').length == 1) {
            elem.find('.coupon-model .decrease').hide();
        }
    }
}

/*
 * 新增活动
 * @date 2016/4/29
 */
function initAddPanel(layero, id) {
    var layerIframe = layero.find('iframe:first-child').contents();
//    getCouponList(layerIframe.find("#coupon"), layerIframe);
    selectCoupon(layerIframe);
    addCouponModel(layerIframe);
    getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe);
    addLinesModel(layerIframe);
    changeTimeNode(layerIframe);
    selectChannel(layerIframe);
    bussinessMark(layerIframe);
    back(layerIframe);
    layerIframe.find("#save").on("click", function () {
        if (!checkParam(layerIframe)) {
            layer.msg('请重新填写选项!', {icon: 2, time: 1000/*1秒后自动关闭*/});
            return;
        }
        var param = createParam(layerIframe, id);
        var layerIndex = layer.msg('新增中。。。', {icon: 16, time: 3600000, shade: [0.5, '#fff']});
        $.ajax({
            type: "POST",
            url: "/activitymanager/add",
            contentType: "application/json",
            dataType: "json",
            data: param,
            success: function (data) {
                layer.close(layerIndex); //关闭加载层
                if (data.status == 0) {
                    layer.msg('添加成功！', {icon: 1, time: 1000}, function () {
                        is_incity = -1;
                        layer.closeAll();
                        list();
                    });
                } else if (data.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(data.message);
                }
            },
            error: function () {
                layer.close(layerIndex); //关闭加载层
                bbx_alert_error('出错啦~');
            }
        });
    });
}


/*
 * 获取优惠券
 * @date 2016/5/7
 */
//function getCouponList(couponElem, layerIframe, setValue) {
//    var params = JSON.stringify({
//        "whenexpire": -1,
//        "line": '',
//        "type": -1,
//        "business": -1,
//        "pattern": '',
//        'pos': 0,
//        'limit': 1000
//    });
//    $.ajax({
//        type: "POST",
//        url: "/couponmanager/glist",
//        contentType: "application/json",
//        dataType: "json",
//        data: params,
//        success: function (data) {
//            if (data.status == 0) {
//                var couponItem = [];
//                var defaultValue;
//                for (var i = 0; i < data.data.length; i++) {
//                    var target = -1;
//                    if (setValue) {
//                        if (data.data[i].id == setValue) {
//                            //设置已选优惠券
//                            defaultValue = {
//                                id: data.data[i].id,
//                                name: data.data[i].friendlyid + '-' + data.data[i].name
//                            };
//                        }
//                    }
//                    if (data.data[i].data.whenexpire == 2) {//绝对过期
//                        var currentTimestamp = parseInt(new Date().getTime());//当前时间戳
//                        var expireTimestamp = new Date(data.data[i].data.expiretime.replace(/-/g, '/')).getTime();
//                        target = expireTimestamp;
////                        console.log('current: ' + currentTimestamp + '; expire: ' + expireTimestamp);
//                        if (expireTimestamp <= currentTimestamp) {
//                            continue;
//                        }
//                    }
//                    couponItem.push({
//                        id: data.data[i].id,
//                        name: data.data[i].friendlyid + '-' + data.data[i].name,
//                        target: target
//                    });
//                }
//                //过滤优惠券
//                var filtCouponFuntion = function (data) {
//                    return filtCoupon(layerIframe, data);
//                };
//                $.selectSuggest(couponElem, couponItem, filtCouponFuntion, '', layerIframe, defaultValue);
//            } else if (data.status == -501) {//session过期
//                window.location.href = '/timeout/index';
//            } else {
//                bbx_alert_error(data.message);
//            }
//        },
//        error: function (data) {
//            bbx_alert_error(data.message);
//        }
//    });
//}

// 选择节点————切换
function changeTimeNode(elem) {
    elem.find('#timenode').change(function () {
        var checkIndex = $(this).get(0).selectedIndex;
        if (checkIndex == 0) {
            elem.find('.form-node-box').hide();
        } else {
            elem.find('.form-node-box').show();
        }
    });
}

// 点击选择优惠券
function selectCoupon(elem) {
    elem.find('.coupon-list-model').delegate(".auto-complete", "click", function () {
        var endTime = elem.find('#endtime').val();
        var endTimestamp = endTime ? new Date(endTime.replace(/-/g, '/')).getTime() : -1;
        var obj = $(this);

        var index = layer.open({
            type: 2,
            shadeClose: false,
            area: ['1000px', '520px'],
            content: '/couponlist/list?endTimestamp=' + endTimestamp,
            success: function (layero, index) {
                initSelectCoupon(layero, index, obj);

            }
        });
    });
}

function initSelectCoupon(layero, index, obj) {
    var layerIframe = layero.find('iframe:first-child').contents();
    layerIframe.find('#list').delegate("tr", "click", function () {
        if ($(this).hasClass('invalid')) {
            return;
        }
        var id = $(this).children('td').eq(0).text();
        var num = $(this).children('td').eq(1).text();
        var name = $(this).children('td').eq(2).text();
        var expiretime = $(this).children('td').eq(3).text();
        console.log(id + ' ' + num + ' ' + name + ' ' + expiretime);
        console.log(obj.attr('id'));
        obj.val(num + '-' + name);
        obj.attr('data', id);
        obj.attr('target', expiretime);
        layer.close(index);
    });
}

//点击选择渠道
function selectChannel(elem) {
    elem.delegate("#channel", "click", function () {
        var obj = $(this);
        var index = layer.open({
            type: 2,
            shadeClose: false,
            area: ['1000px', '520px'],
            content: '/channellist/list',
            success: function (layero, index) {
                initSelectChannel(layero, index, obj);
            }
        });
    });
}

function initSelectChannel(layero, index, obj) {
    var layerIframe = layero.find('iframe:first-child').contents();
    layerIframe.find('#list').delegate("tr", "click", function () {
        var channel = $(this).children('td').eq(0).text();
        var name = $(this).children('td').eq(1).text();
        console.log(channel + ' ' + name);
        console.log(obj.attr('id'));
        obj.val(name);
        obj.attr('data', channel);
        layer.close(index);
    });
}

//构造参数
function createParam(layerIframe, id) {
    var usableline = [];
    if (layerIframe.find("#timenode option:selected").val() != "1") {
        usableline = routeSelect(layerIframe);
    } else { //登陆
        usableline = new Array("*");
    }
    var param = JSON.stringify({
        'id': id ? id : '',
        "name": layerIframe.find("#name").val(),
        "tag": layerIframe.find("#tag").val(),
        "starttime": layerIframe.find("#starttime").val(),
        "endtime": layerIframe.find("#endtime").val(),
        "user": Number(layerIframe.find("#user option:selected").val()),
        "channel": layerIframe.find("#channelnolimit").is(':checked') ? '' : layerIframe.find("#channel").attr('data'),
        "coupon": couponSelect(layerIframe),
        "timenode": Number(layerIframe.find("#timenode option:selected").val()),
        "line": usableline,
        "business": businessSelect(layerIframe),
        "maxcount": layerIframe.find("#maxcountnolimit").is(':checked') ? -1 : Number(layerIframe.find("#maxcount").val()),
        "countperuser": layerIframe.find("#countperusernolimit").is(':checked') ? -1 : Number(layerIframe.find("#countperuser").val())
    });
    console.log(param);
    return param;
}

//获取选择的优惠券列表
function couponSelect(elem) {
    var coupons = [];
    elem.find('.coupon-list-model .coupon-model').each(function () {
        var cou = {
            id: $(this).find('.auto-complete').attr('data'),
            cnt: Number($(this).find('.form-sm-input').val())
        };
        var i = 0;
        for (; i < coupons.length; i++) {
            if (coupons[i].id == cou.id) {
                coupons[i].cnt += cou.cnt;
                break;
            }
        }
        if (i == coupons.length) {
            coupons.push(cou);
        }
    });
    return coupons;
}

//获取选择的业务
function businessSelect(elem) {
    var business = 0;
    if (elem.find("#timenode option:selected").val() != "1") {
        if (elem.find("#busAll").prop("checked")) {
            business = -1;
        } else {
            elem.find("#business input:checked").each(function () {
                business += parseInt($(this).attr('val'));
            });
        }
    } else { //登陆
        business = -1;
    }
    return business;
}

//修改活动
function initModifyCoupon(layero, id) {
    var layerIframe = layero.find('iframe:first-child').contents();
    selectCoupon(layerIframe);
    addCouponModel(layerIframe);
    addLinesModel(layerIframe);
    changeTimeNode(layerIframe);
    selectChannel(layerIframe);
    bussinessMark(layerIframe);
    back(layerIframe);
    fillDetailInfo(layerIframe, id);
    modify(layerIframe, id);
}

//填充活动详情
function fillDetailInfo(layerIframe, id) {
    $.ajax({
        type: "POST",
        url: "/activitymanager/gactinfo",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({"id": id}),
        success: function (data) {
            if (data.status == 0) {
                _fillDetailInfo(layerIframe, data.data);
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            bbx_alert_error("出错啦~");
        }
    });
}

//获取优惠券
function getCoupon(id, couponElem) {
    $.ajax({
        type: "POST",
        url: "/couponmanager/ginfonoparse",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({"id": id}),
        success: function (data) {
            if (data.status == 0) {
//                console.log(data);
                couponElem.val(data.friendlyid + '-' + data.name);
                couponElem.attr('data', data.id);
                var expiretime = -1;
                if (data.data.whenexpire == 2) {//绝对过期
                    expiretime = data.data.expiretime * 1000;
                }
                couponElem.attr('target', expiretime);
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            bbx_alert_error("出错啦~");
        }
    });
}

function _fillDetailInfo(layerIframe, data) {
    layerIframe.find("#name").val(data.name);//名称
    layerIframe.find("#starttime").val(data.starttime); //开始时间
    layerIframe.find("#endtime").val(data.endtime);//结束时间
    layerIframe.find("#user option[value='" + data.targetuser + "']").attr("selected", true);//用户
    if (data.rewards) {//优惠券列表
        for (var i in data.rewards) {
            if (i == 0) {
                getCoupon(data.rewards[i].id, layerIframe.find("#coupon"));
                layerIframe.find("#couponcnt").val(data.rewards[i].cnt);
            } else {
                _addCouponModel(layerIframe.find('.coupon-buttons .increase'), layerIframe, true, data.rewards[i].id, data.rewards[i].cnt);
            }
        }
    } else {
//        getCouponList(layerIframe.find("#coupon"), layerIframe);
    }
    layerIframe.find("#timenode option[value='" + data.timenode + "']").attr("selected", true);//获得节点
    if (data.timenode != '1') {//非登陆
        layerIframe.find('.form-node-box').show();

        var busi = data.targetbusiness; //业务
        if (busi == -1) {
            layerIframe.find("input[type='checkbox']").prop("checked", true);
        } else {
            var busiArray = new Array(0, 0, 0, 0);
            for (var i = 3; i >= 0; i--) {
                var j = parseInt(busi / (Math.pow(2, i)));
                if (j > 0) {
                    busiArray[i] = 1;
                }
                busi %= (Math.pow(2, i));
                if (busi == 0) {
                    break;
                }
            }
            if (busiArray[0]) {
                layerIframe.find("#citypin").prop("checked", true);
            }
            if (busiArray[1]) {
                layerIframe.find("#citybao").prop("checked", true);
            }
            if (busiArray[2]) {
                layerIframe.find("#package").prop("checked", true);
            }
            if (busiArray[3]) {
                layerIframe.find("#city").prop("checked", true);
                if (!busiArray[0] && !busiArray[1] && !busiArray[2]) {
                    is_incity = 1;
                }
            } else {
                is_incity = 0;
            }
        }
        if (data.targetline) {//路线
            for (var i = 0; i < data.targetline.length; i++) {
                if (data.targetline[i] == "*") {
                    layerIframe.find("#routeAll").attr("checked", true);
                    getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe);
                    break;
                }
                var line = data.targetline[i].line_id.split("_to_");
                if (i == 0) {
                    layerIframe.find("#routePart").attr("checked", true);
                    layerIframe.find("#routePartcss").removeClass('display-none');
                    getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe, line[0], line[1]);
                } else {
                    _addLinesModel(layerIframe.find('.line-buttons .increase'), layerIframe, true, line[0], line[1]);
                }
            }
        } else {
            getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe);
        }
    } else {//登陆
        layerIframe.find("#busAll").prop("checked", true);
        layerIframe.find("input[name='checkbox']").prop("checked", true);
        layerIframe.find("#routeAll").attr("checked", true);
        getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe);
    }
    if (data.channel) {
        layerIframe.find("#channel").attr('data', data.channel.channel);//渠道
        layerIframe.find("#channel").val(data.channel.name);
    } else {
        layerIframe.find("#channelnolimit").attr("checked", true);
    }
    if (data.totalcount > -1) {
        layerIframe.find("#maxcount").val(data.totalcount);//奖励总份数
    } else {
        layerIframe.find("#maxcountnolimit").attr("checked", true);
    }
    if (data.countperuser > -1) {
        layerIframe.find("#countperuser").val(data.countperuser);//单人最多可得份数
    } else {
        layerIframe.find("#countperusernolimit").attr("checked", true);
    }
    layerIframe.find("#tag").val(data.tag);//标记
    setNum(layerIframe.find("#tag"), 16, layerIframe.find("#tagEnNum"), layerIframe.find("#tagEnNum1"), layerIframe.find("#tagmark"), 1);
}

//修改
function modify(layerIframe, id) {
    layerIframe.find("#modify").on("click", function () {
        if (!checkParam(layerIframe)) {
            layer.msg('请重新填写选项!', {icon: 2, time: 1000/*1秒后自动关闭*/});
            return;
        }
        var param = createParam(layerIframe, id);
        var layerIndex = layer.msg('修改中。。。', {icon: 16, time: 3600000, shade: [0.5, '#fff']});
        $.ajax({
            type: "POST",
            url: "/activitymanager/modify",
            contentType: "application/json",
            dataType: "json",
            data: param,
            success: function (data) {
                layer.close(layerIndex); //关闭加载层
                if (data.status == 0) {
                    layer.msg('修改成功！', {icon: 1, time: 1000}, function () {
                        is_incity = -1;
                        layer.closeAll();
                        list();
                    });
                } else if (data.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(data.message);
                }
            },
            error: function () {
                layer.close(layerIndex); //关闭加载层
                bbx_alert_error('出错啦~');
            }
        });
    });
}

//检查参数
function checkParam(layerIframe) {
    var rightParam = true;
    layerIframe.find("#name").val() ? layerIframe.find("#namemark").text('') : (layerIframe.find("#namemark").text('请填写！'), rightParam = false);
    layerIframe.find("#starttime").val() && layerIframe.find("#endtime").val() ? layerIframe.find("#endtimemark").text('') : (layerIframe.find("#endtimemark").text('请填写！'), rightParam = false);
    var allCouponRight = true;
    layerIframe.find('.coupon-list-model .coupon-model').each(function () {
        if (!$(this).find('.auto-complete').val() || !$(this).find('.form-sm-input').val()) {
            allCouponRight = false;
        }
    });
    allCouponRight ? layerIframe.find("#couponmark").text('') : (layerIframe.find("#couponmark").text('请填写优惠券及其数量！'), rightParam = false);
    if (layerIframe.find("#timenode option:selected").val() != "1") {
        if (layerIframe.find("#routePart").attr("checked")) {
            var allRouteRight = true;
            layerIframe.find('.route-part-control .line-model').each(function () {
                if (!$(this).find('.auto-complete:first-child').val() || !$(this).find('.auto-complete:nth-child(2)').val()) {
                    allRouteRight = false;
                }
            });
            allRouteRight ? layerIframe.find("#routePartmark").text('') : (layerIframe.find("#routePartmark").text('请选择线路！'), rightParam = false);
        }
        var allBusinessNotChecked = true;
        layerIframe.find("#business input").each(function () {
            if ($(this).prop("checked")) {
                allBusinessNotChecked = false;
            }
        });
        allBusinessNotChecked ? (layerIframe.find("#businessmark").text('请选择业务类型！'), rightParam = false) : layerIframe.find("#businessmark").text('');
    }
    if (layerIframe.find("#channelnolimit").is(':checked')) {
        layerIframe.find("#channelmark").text('');
    } else {
        layerIframe.find("#channel").val() ? layerIframe.find("#channelmark").text('') : (layerIframe.find("#channelmark").text('请选择渠道！'), rightParam = false);
    }
    if (layerIframe.find("#maxcountnolimit").is(':checked')) {
        layerIframe.find("#maxcountmark").text('');
        if (layerIframe.find("#countperusernolimit").is(':checked')) {
            layerIframe.find("#countperusermark").text('');
        } else {
            layerIframe.find("#countperuser").val() ? layerIframe.find("#countperusermark").text('') : (layerIframe.find("#countperusermark").text('请填写！'), rightParam = false);
        }
    } else {
        layerIframe.find("#maxcount").val() ? layerIframe.find("#maxcountmark").text('') : (layerIframe.find("#maxcountmark").text('请填写！'), rightParam = false);
        var errorText = '';
        if (layerIframe.find("#countperusernolimit").is(':checked')) {
            errorText = '单人最多可得份数不能超过奖励总份数！';
            rightParam = false;
        } else {
            if (!layerIframe.find("#countperuser").val()) {
                errorText = '请填写！';
                rightParam = false;
            } else if (Number(layerIframe.find("#countperuser").val()) > Number(layerIframe.find("#maxcount").val())) {
                errorText = '单人最多可得份数不能超过奖励总份数！';
                rightParam = false;
            }
        }
        layerIframe.find("#countperusermark").text(errorText);
    }
    if (layerIframe.find("#tag").val()) {
        layerIframe.find("#tagremark").text('');
        if (layerIframe.find("#tag").val().replace(/[\u4e00-\u9fa5]/g, "**").length > 16) {
            layerIframe.find("#tagmark").addClass('mandatory');
            rightParam = false;
        }
    } else {
        layerIframe.find("#tagremark").text('请填写！');
        rightParam = false;
    }

    return rightParam;
}